package jeecg.business.thread.task.impl;

import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import jeecg.business.entity.enter.EnterEntity;
import jeecg.business.entity.keyinfo.KeyinfoEntity;
import jeecg.business.entity.keyword.KeywordEntity;
import jeecg.business.entity.log.CollLogEntity;
import jeecg.business.entity.site.SiteEntity;
import jeecg.business.thread.HtmlFetchManage;
import jeecg.business.vo.ProxyIpVo;

import org.apache.commons.lang.math.RandomUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.clean.CommonHtmlCleanUtil;
import org.jeecgframework.core.util.clean.bean.FetchListInfo;
import org.jeecgframework.core.util.clean.bean.HtmlParseResult;
import org.jeecgframework.core.util.clean.bean.InfoParam;
import org.jeecgframework.core.util.http.HttpClientUtil;

/**
 * 
 * <p>
 * 标题: 微信
 * </p>
 * <p>
 * 描述: // TODO
 * </p>
 * 
 * @author LinYingPiaoJian(Q:71426052)
 * @version // TODO
 * @since 2015-6-6 下午10:05:02
 */
public class WeixinExecTask_bak extends CommonExecTask{
	
	String ip;
	
	int port;
	
	
	public WeixinExecTask_bak(EnterEntity enter , KeywordEntity keyword, SiteEntity site ) {
		super(enter , keyword, site);
	}
	
	void getIpAndPort(){
		ProxyIpVo ips;
		try {
			ips = HtmlFetchManage.getIpCanUsed();
//			System.out.println("获取到IP："+ips.getIpandport());
			String []ipport = ips.getIpandport().split(":");
			ip = ipport[0];
			port = Integer.parseInt(ipport[1]);
		} catch (Exception e) {
			
		}
	}
	
	public void setCookies(){
		String baseurl = getFetchHtml();
		
		String html = null;
		

		if(HtmlFetchManage.proxyIsUse == 1){
			do{
				getIpAndPort();
				html = HttpClientUtil.getSourceFromUrl(baseurl, site.getWyzfj(), null , ip , port);
				System.out.println("切换一个ip，打印避免死循环");
			}while(StringUtil.isEmpty(html) || !html.contains("搜狗"));
			System.out.println(ip+"  ----------------  "+port);
		}else{
			html = HttpClientUtil.getSourceFromUrl(baseurl, site.getWyzfj(), null);
		}
		
		/**
		 * 提出SNUID=1AA5D255FAFFEE20317DC7C1FA93DD90;
		 */
//		String snuid = "";
//		if(html.indexOf("SNUID") >= 0){
//			snuid = html.substring(html.indexOf("SNUID"),html.indexOf(";", html.indexOf("SNUID")));
//		}
//		
//		cookies = HttpClientUtil.getCookies(site.getZddz(), site.getWyzfj());
//		/**
//		 * SUV为随机数
//		 */
//		cookies += snuid+";SUV=00D415097D58FFAF55027B71C4E25768";
//		
//		System.out.println("cookies："+cookies);
	}
	
	public void setCookies(String url){
		do{
			cookies = HttpClientUtil.getCookies4Weixin(url, site.getWyzfj(), null , ip , port);
			if(StringUtil.isEmpty(cookies) || !cookies.contains("SNUID=") || !cookies.contains("SUV=")){
				cookies = null;
				setCookies();
			}
		}while(cookies == null);
		System.out.println("cookies："+cookies);
	}
	
	
	
	public void run(){
//		if(StringUtil.isEmpty(ip)) return;
		CollLogEntity log = null;
		log = saveLog();
		try{
			System.out.println("exec weixin task......");
			String basehref = site.getZddz();
			String word = URLEncoder.encode(keyword.getKeyword(),site.getWyzfj());
			basehref = basehref.replace(KEYWORD_FLAG, word);
			String paramBaseHref = basehref;
			setCookies();
			do{
				current++;
				if(StringUtil.isNotEmpty(basehref)){
					FetchListInfo info = CommonHtmlCleanUtil.getListUrl4Proxy(basehref, site , cookies , ip , port);
					if("param".equals(site.getXyyhqfs())){
						if(!basehref.contains("{page}")) basehref = paramBaseHref + "&"+site.getLbxyy()+"={page}";
						basehref = basehref.replace("{page}", (current+1)+"");
						info.setNextPage(basehref);
					}else{
						basehref = info.getNextPage();
					}
					List<String> urlList = info.getHrefList();
					if(urlList!=null && urlList.size()>0){
						
						HtmlParseResult result = null;
						KeyinfoEntity keyinfo = null;
						for(String url : urlList){
							if(!url.startsWith("http")) url = site.getGdz()+url;
							if(keyinfoService.hasHref(url , enter.getId())) continue;
							/**
							 * 单个错误时跳过
							 */
							if(cookies == null) setCookies(url);
							try{
								InfoParam infoparam = new InfoParam();
								infoparam.setListInfo(info);
								/**
								 * 二次跳转
								 */
								result = CommonHtmlCleanUtil.getInfo4proxy(url, site, keyword.getKeyword() , cookies , infoparam , ip , port);
								keyinfo = new KeyinfoEntity(result);
								keyinfo.setQyid(enter.getId());
								if(filter(enter, keyinfo , keyword))		//过滤
									keyinfoService.saveKeyinfo(keyinfo);
							}catch(Exception e1){
//								e1.printStackTrace();
							}							
						}
						
					}
				}
				if("wx".equals(site.getJclx())){
					Thread.sleep((15+RandomUtils.nextInt(10))*1000);
				}
			}while(current <= maxpage);
//			log = collLogService.get(CollLogEntity.class, log.getId());
		}catch(Exception e){
//			e.printStackTrace();
//			log.setSfcg("2");
//			log.setCwxx(e.getMessage());
		}finally{
			log = collLogService.get(CollLogEntity.class, log.getId());
			log.setJssj(new Date());
			collLogService.updateEntitie(log);
			System.out.println("end....");
		}		
	}

}
